<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('组装拆卸新增及修改')" />
	<th:block th:include="include :: businessCSS" />
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
	    <div class="north">
            <th:block th:include="include :: business_btn" />
	        <th:block th:include="include :: business_tpl('top')" />
    	</div>
	    <div class="mid-content">
	        <table class="layui-hide" id="dhtable" lay-filter="ftable"></table>
	    </div>
	    <div class="mid-content">
	        <table class="layui-hide" id="dhtable1" lay-filter="ftable1"></table>
	    </div>
	    <th:block th:include="include :: pageFooter" /> 
        </form>
	</div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: businessTableBtn" />
<!-- 组装拆卸入库表头按钮 -->
<script type="text/html" id="toolbar1">
<div class="layui-btn-container">
	<div th:if="${buttonStateOn['takeon-addbtn']} neq 'hidden'" 
		th:class="${buttonStateOn['takeon-addbtn']} eq 'enable'?'layui-btn layui-btn-normal layui-table-tools':'layui-btn layui-table-tools layui-btn-disabled'" 
		th:lay-event="${buttonStateOn['takeon-addbtn']} eq 'enable'?'addBtn':''">
		<i class="dhicon dh-plus"></i> 新增
	</div>
	<div th:if="${buttonStateOn['deletebatch']} neq 'hidden'"
		th:class="${buttonStateOn['deletebatch']} eq 'enable'?'layui-btn layui-btn-danger layui-table-tools':'layui-btn layui-table-tools layui-btn-disabled'" 
		th:lay-event="${buttonStateOn['deletebatch']} eq 'enable'?'deleteBatch':''">
		<i class="dhicon dh-remove"></i> 删除
	</div>
	<div th:if="${buttonStateOn['takeon-importbtn']} neq 'hidden'"
		th:class="${buttonStateOn['takeon-importbtn']} eq 'enable'?'layui-btn layui-table-tools importbtn-bg':'layui-btn layui-table-tools layui-btn-disabled'" 
		th:lay-event="${buttonStateOn['takeon-importbtn']} eq 'enable'?'importBtn':''">
		<i class="dhicon dh-upload"></i> 导入
	</div>
	<div th:if="${buttonStateOn['tp-callin']} neq 'hidden'"
		th:class="${buttonStateOn['tp-callin']} eq 'enable'?'layui-btn layui-table-tools relation':'layui-btn layui-table-tools layui-btn-disabled'" 
		th:style="${buttonStateOn['tp-callin']} eq 'enable'?'background:tomato':''">
		<i class="layui-icon layui-icon-upload-circle"></i> 调入
	</div>
	<div class="layui-btn layui-table-tools relation" id="relation" style="background:white;">
		<p th:each="ObjOn:${relationObjOn}" style="width: 200px;background:white;margin: 0 -20px;box-shadow:1px 1px 10px rgba(0,0,0,0.2)">
			<a th:text="${ObjOn.key}" th:value="${ObjOn.value}" onclick="relationIn(this)" th:moduleTable="${gridColumnsOn.moduleTable}"></a>
		</p>
	</div>
</div>
</script>
<!-- 组装入库导入区域 -->
<script id="importTpl" type="text/template">
<form enctype="multipart/form-data" class="mt20 mb10">
	<div class="col-xs-offset-1">
		<input type="file" id="file" name="file"/>
		<div class="mt10 pt5">
			 <a onclick="$.tablelist.importTemplate('/business/take/takeon/exporttemplate')" class="btn btn-default btn-xs"><i class="dhicon dh-file-excel-o"></i> 下载模板</a>
		</div>
		<font color="red" class="pull-left mt10">
			提示：仅允许导入“xls”或“xlsx”格式文件！
		</font>
	</div>
</form>
</script>
<!-- 明细特殊模板自生成 -->
<div th:each="dfpl : ${gridColumnsOn.dictionaryForPageFieldList}" th:remove="tag">
	<script type="text/html" th:if="${(dfpl.fieldFrontType eq 't_date' or dfpl.fieldFrontType eq 't_datetime')}" th:id="'date_'+${dfpl.fields}">
		<input type="text" th:value="'{{d.'+${dfpl.fields}+'?d.'+${dfpl.fields}+':``}}'" th:fft="${dfpl.fieldFrontType}" class="layui-input layui-table-date" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" autocomplete="off">
		<i class="dhicon dh-calendar icon_date_business" style="z-index:3;font-size:0"></i>
	</script>
	<script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontext'}" th:id="'buttontext_'+${dfpl.fields}">
		<span th:text="'{{d.'+${dfpl.fields}+'}}'"></span>
		<i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]],false,false,false,gridColumns.gridBody,'dhtable1',listData1)" style="position:absolute;right:8px;z-index:3"></i>
	</script> 
	<script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontextedit'}" th:id="'buttontextedit_'+${dfpl.fields}">
		<input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" th:onkeyup="inputOnTable(this,[[${dfpl.fields}]])" autocomplete="off">
		<i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]],false,false,false,gridColumns.gridBody,'dhtable1',listData1)" style="position:absolute;right:8px;z-index:3"></i>
	</script>
	<script type="text/html" th:if="${dfpl.fieldFrontType eq 't_textarea' or (dfpl.fieldFrontType eq 't_textarea' and gridColumns.readOnly)}" th:id="'textarea_'+${dfpl.fields}">
		<span th:utext="'{{typeof d.'+${dfpl.fields}+' !== \'undefined\' && d.'+${dfpl.fields}+' !== null?d.'+${dfpl.fields}+':\'\'}}'"></span>
		<i class="layui-icon layui-icon-form detail-edit" th:onclick="textareaBox(this,[[${dfpl.fields}]],[[${dfpl.fieldName}]],[[${gridColumns.readOnly}]])" style="float:right;z-index:999"></i>
	</script>
	<script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdown'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdown_'+${dfpl.fields}">
		<select th:data-field="${dfpl.fields}" th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}" lay-filter="select_table" fft="t_dropdown">
			<option></option>
			<div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
		</select>
	</script>
	<script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdownedit'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdownedit_'+${dfpl.fields}">
   	 	<input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;width: calc(100% - 33px);height: 30px;margin-top: 1px;margin-left: -7px;" th:onkeyup="inputSearchTable(this,[[${dfpl.fields}]])" autocomplete="off">
	    <select th:lay-filter="${dfpl?.fields}+'_select'" autocomplete="off" class="layui-select" lay-search th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}">
			<option></option>
			<div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
		</select>
	</script>
	<script type="text/html" th:if="${dfpl.fieldFrontType eq 't_checkbox'}" th:id="'checkbox_'+${dfpl.fields}">
		<div th:utext="'<input type=\'checkbox\' value=\'true\' lay-skin=\'switch\' tName='+${dfpl.fields}+' tIndex=\'{{d.LAY_TABLE_INDEX}}\' lay-filter=\'switchTable\' lay-text=\'是|否\' data-field='+${dfpl.fields}+' {{d.'+${dfpl.fields}+'?\'checked\':\'\'}} '+(${dfpl.fieldFrontEdit or #bools.isTrue(checkProcessTask)}?'':'disabled')+'>'" th:remove="tag"><div>
	</script>
	<script type="text/html" th:if="${dfpl.fieldFrontType eq 't_file'}" th:id="'file_'+${dfpl.fields}">
		<span th:text="'{{d.'+${dfpl.fields}+'}}'"></span>
		<i class="layui-icon layui-icon-upload getDetailUpload" tGuid="{{d.guid}}" th:tName="${dfpl.fields}" style="float:right"></i>
	</script>
</div>
<!-- 自生成结束 -->
<th:block th:include="include :: inlineJS" />
<script th:inline="javascript">
    /*<![CDATA[*/
	var gridColumnsOn=[[${gridColumnsOn}]],
		importFieldsOn=[[${importFieldsOn}]],
		buttonStateOn=[[${buttonStateOn}]],
		relationObjOn=[[${relationObjOn}]];
    /*]]>*/
</script>
<script type="text/javascript">
var $,layer,form,table,laydate,element;//定义layui模块
var dataStr1=[],listData1,fieldFrontEditList1=[],totalList1={};
eachFields();//明细表格中的字段遍历（默认处理）
$.each(gridColumnsOn.dictionaryForPageFieldList,function(i,v){//明细表格中不可编辑字段（子表）
	// if(v.fieldFrontEdit == false && v.fieldFrontHidden == false)fieldFrontEditList1.push(v.fields);
	if(v.fieldFrontEdit == false)fieldFrontEditList1.push(v.fields);
});
$.each(gridColumns.gridBody,function(i,v){//统计合计列数组
	if(v.totalRow && !v.hide)totalList[v.field]=i;
})
$.each(gridColumnsOn.gridBody,function(i,v){//统计合计列数组
	if(v.totalRow && !v.hide)totalList1[v.field]=i;
})
$.each(gridColumnsOn.gridNewLine,function(v,k){//明细新增模板修改默认值（子表）
	if(k.substring(0,1)=='#')gridColumnsOn.gridNewLine[v]=$(k).val();
})
layui.use(['laydate', 'table','form','layer','jquery','util','element'], function () {
 	$ = layui.$,layer = layui.layer,form = layui.form,table = layui.table,laydate = layui.laydate,util = layui.util,element=layui.element;
 	beforeInit();//表单初始化之前的动作集合
 	layui.element.render();
 	$.get("/business/take/listbynid?nid="+nid,function(data){
		$.each(data.data,function(k,v){
			dataStr.push(v);
		});
		$.tablelist.init({
			elem: '#dhtable'
			,data: dataStr
			,page: false
			,even: gridColumns.readOnly
			,limit: 1000
			,totalRow: gridColumns.totalRow
	   		,cols: [gridColumns.gridBody
			]
			,toolbar: "#toolbar"
			,defaultToolbar: [{title:'列设置',layEvent: 'fieldSet',icon: 'layui-icon-set'}]
			,height:'full-550'
			,done:function(res, curr, count){
				listData = table.cache.dhtable;//每次重载都赋值更新表缓存
				if(!gridColumns.readOnly)tableDone(listData,fieldFrontEditList);//非只读情况下的动作集
				showloadings(false);
				detailUpload();
			}
		});
		//请求结束后才初始化表格，在出库之后才请求，防止入库提前初始化
	 	$.get("/business/take/takeon/listbynid?nid="+nid,function(data){
			$.each(data.data,function(k,v){
				dataStr1.push(v);
			});
			$.tablelist.init({
				elem: '#dhtable1'
				,data: dataStr1
				,page: false
				,even: gridColumnsOn.readOnly
				,limit: 1000
				,totalRow: gridColumnsOn.totalRow
		   		,cols: [gridColumnsOn.gridBody
				]
				,toolbar: '#toolbar1'
				,defaultToolbar: [{title:'列设置',layEvent: 'fieldSet',icon: 'layui-icon-set'}]
				,height:'full-550'
				,done:function(res, curr, count){
					listData1 = table.cache.dhtable1;//每次重载都赋值更新表缓存
					if(!gridColumns.readOnly)tableDone(listData1,fieldFrontEditList1,true);//非只读情况下的动作集
					showloadings(false);
					detailUpload();
					$('#relation').hide();
					$('.relation').hover(function(){//调入关系显示隐藏
						$('#relation').show();
					},function(){
						$('#relation').hide();
					})
				 	changeDropdownInTable('fCgFpSl',listData1);//表格中的下拉可编辑
				}
			});
		});
	});
 	//头部event事件
	table.on('toolbar(ftable)', function(obj){
		if(obj.config.id=='dhtable')var ld=listData,gdc=gridColumns,checkStatus = table.checkStatus('dhtable'),md=moduleTable,ifs=importFields;
		else var ld=listData1,gdc=gridColumnsOn,checkStatus = table.checkStatus('dhtable1'),md=gridColumnsOn.moduleTable,ifs=importFieldsOn;
	    switch(obj.event){
	    	case 'deleteBatch':
	    		tableDeleteBatch(obj.config.id, ld, checkStatus);
	    	break;
	    };
	});
	//头部event事件
	table.on('toolbar(ftable1)', function(obj){
		if(obj.config.id=='dhtable')var ld=listData,gdc=gridColumns,checkStatus = table.checkStatus('dhtable'),md=moduleTable,ifs=importFields;
		else var ld=listData1,gdc=gridColumnsOn,checkStatus = table.checkStatus('dhtable1'),md=gridColumnsOn.moduleTable,ifs=importFieldsOn;
	    switch(obj.event){
	    	case 'addBtn':
	    		if(ld.length > 0){
	    			if(ld[ld.length - 1]['iid']){
	    				gdc.gridNewLine.iid = Number(ld[ld.length - 1]['iid']) + 1;//行号自增1
	    			}else{
	    				gdc.gridNewLine.iid = 1;
	    			}
	    		}else{
	    			gdc.gridNewLine.iid = 1;
	    		}
	    		ld.push(gdc.gridNewLine);
	        	table.reload(obj.config.id, {data : ld});
	      		form.render();
	    	break;
	    	case 'deleteBatch':
	    		tableDeleteBatch(obj.config.id, ld, checkStatus);
	    	break;
	    	case 'fieldSet':
	    		filedSet(md);
         	break;
			case 'tableFull'://表格展开
				$('.north .layui-form').hide();
				table.reload('dhtable',{
					defaultToolbar: [{title:'收缩',layEvent:'tableShrink',icon:'layui-icon-screen-restore'}],
					height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
				});
			break;
			case 'tableShrink'://表格收缩
				$('.north .layui-form').show();
				table.reload('dhtable',{
					defaultToolbar: [{title:'展开',layEvent:'tableFull',icon:'layui-icon-screen-full'}],
					height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
				});
			break;
	    	case 'importBtn':
	    		$.tablelist.importExcel(obj.config.id,ifs, ld, md, decimalObj);
         	break;
	    };
	});
	toolEvent('ftable');//行event事件监听
	table.on('sort(ftable)', function(obj){//监听排序——重载赋值渲染
		for(var i=1; i<listData.length; i++){//冒泡排序
			for(var j=0; j<listData.length-i; j++){
				if(obj.type=='asc' && listData[j][obj.field]<listData[j+1][obj.field]){
					listData[j]=[listData[j+1],listData[j+1]=listData[j]][0];
				}
				if(obj.type=='desc' && listData[j][obj.field]>listData[j+1][obj.field]){
					listData[j]=[listData[j+1],listData[j+1]=listData[j]][0];
				}
		    }
		}
		table.render('dhtable', {data:listData,initSort: obj});
		if(!gridColumns.readOnly)tableDone(listData,fieldFrontEditList);//非只读情况下的动作集
		showloadings(false);
		detailUpload();
	});
	table.on('sort(ftable1)', function(obj){//监听排序——重载赋值渲染
		for(var i=1; i<listData1.length; i++){//冒泡排序
			for(var j=0; j<listData1.length-i; j++){
				if(obj.type=='asc' && listData1[j][obj.field]<listData1[j+1][obj.field]){
					listData1[j]=[listData1[j+1],listData1[j+1]=listData1[j]][0];
				}
				if(obj.type=='desc' && listData1[j][obj.field]>listData1[j+1][obj.field]){
					listData1[j]=[listData1[j+1],listData1[j+1]=listData1[j]][0];
				}
		    }
		}
		table.render('dhtable1', {data:listData1,initSort: obj});
		if(!gridColumns.readOnly)tableDone(listData1,fieldFrontEditList1,true);//非只读情况下的动作集
		showloadings(false);
		detailUpload();
	});
	table.on('edit(ftable)', function(obj){
		var selector = obj.tr.selector+' td[data-field="'+obj.field+'"] div';
        var oldtext = $("[lay-id='dhtable']").find(selector).text();// 单元格编辑之前的值
		var editField = obj.field,//编辑单元格
			editRow = obj.data,//编辑单元格行数据
			dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
			isReturn,editValue;
		if(decimalObj[obj.field] > -1){//判断是否数值字段
			editValue = checkEdit(obj, decimalObj);//判断输入是否为数值，否则还原数值
			if(!editValue){
				editValue = oldtext;
				listData[dataindex][editField] = oldtext;
				isReturn = 1;
			}
			if(!isReturn){//输入的是数值并且改单元格是数值格式字段
				if(editField == 'iid'){//行号
					listData[dataindex]['iid'] = Number(editValue).toFixed(decimalObj.iid);
				}else{
					listData[dataindex]['bNumb'] = Number(listData[dataindex]['bNumb'])?Number(listData[dataindex]['bNumb']).toFixed(decimalObj['bNumb']):0;
					listData[dataindex]['bPrice'] = Number(listData[dataindex]['bPrice'])?Number(listData[dataindex]['bPrice']).toFixed(decimalObj['bPrice']):0;
					if($.inArray(editField,['bNumb','bPrice'])>-1)listData[dataindex][editField] = Number(editValue).toFixed(decimalObj[editField]);
					listData[dataindex]['fSumje'] = (Number(listData[dataindex]['bNumb'])*Number(listData[dataindex]['bPrice'])).toFixed(decimalObj['fSumje']);
					obj.update({
						bNumb:listData[dataindex]['bNumb'],
						bPrice:listData[dataindex]['bPrice'],
						fSumje:listData[dataindex]['fSumje']
					});
				}
				$.each(totalList,function(i,v){//重新计算统计字段数值
					if(i==editField){//编辑单元格为合计列时更新错误（单元格值的改变在监听后）
						$('.laytable-cell-1-0-'+v).last().text(Number(Number($('.laytable-cell-1-0-'+v).last().text())-Number(oldtext)+Number(editValue)).toFixed(decimalObj[i]));
					}else{
						var totalSum=0;
						$.each($('.laytable-cell-1-0-'+v),function(j,k){
							if(j>0 && j<$('.laytable-cell-1-0-'+v).length-1)totalSum+=Number($(k).text());//第一个是标题，最后一个是统计行
							if(j==$('.laytable-cell-1-0-'+v).length-1)$(k).text(totalSum.toFixed(decimalObj[i]));
						})
					}
				})
			}
			setTableValue('dhtable', dataindex, editField, editValue);//通过dom给表格内控件渲染值
			listData[dataindex][editField] = editValue;
		}
	});
	table.on('edit(ftable1)', function(obj){
		var selector = obj.tr.selector+' td[data-field="'+obj.field+'"] div';
        var oldtext = $("[lay-id='dhtable1']").find(selector).text();// 单元格编辑之前的值
		var editField = obj.field,//编辑单元格
			editRow = obj.data,//编辑单元格行数据
			dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
			isReturn,editValue;
		if(decimalObj[obj.field] > -1){//判断是否数值字段
			editValue = checkEdit(obj, decimalObj);//判断输入是否为数值，否则还原数值
			if(!editValue){
				editValue = oldtext;
				listData1[dataindex][editField] = oldtext;
				isReturn = 1;
			}
			if(!isReturn){//输入的是数值并且改单元格是数值格式字段
				if(editField == 'iid'){//行号
					listData1[dataindex]['iid'] = Number(editValue).toFixed(decimalObj.iid);
				}else{
					listData1[dataindex]['bNumb'] = Number(listData1[dataindex]['bNumb'])?Number(listData1[dataindex]['bNumb']).toFixed(decimalObj['bNumb']):0;
					listData1[dataindex]['bPrice'] = Number(listData1[dataindex]['bPrice'])?Number(listData1[dataindex]['bPrice']).toFixed(decimalObj['bPrice']):0;
					if($.inArray(editField,['bNumb','bPrice'])>-1)listData1[dataindex][editField] = Number(editValue).toFixed(decimalObj[editField]);
					listData1[dataindex]['fSumje'] = (Number(listData1[dataindex]['bNumb'])*Number(listData1[dataindex]['bPrice'])).toFixed(decimalObj['fSumje']);
					obj.update({
						bNumb:listData1[dataindex]['bNumb'],
						bPrice:listData1[dataindex]['bPrice'],
						fSumje:listData1[dataindex]['fSumje']
					});
				}
				if(editField == 'bPrice'){//实际进价的计算（隐藏时实时更新，显示时为空赋值）
					$.each(gridColumnsOn.gridBody,function(i,v){
						if(v.field=='fPrice'){
							if(v.hide=="true")listData1[dataindex]['fPrice'] = Number(editValue).toFixed(decimalObj.fPrice);
							else{
								if(!editRow.fPrice)listData1[dataindex]['fPrice'] = Number(editValue).toFixed(decimalObj.fPrice);
							}
							obj.update({fPrice: listData1[dataindex]['fPrice']});
						}
					})
				}
				$.each(totalList1,function(i,v){//重新计算统计字段数值
					if(i==editField){//编辑单元格为合计列时更新错误（单元格值的改变在监听后）
						$('.laytable-cell-2-0-'+v).last().text(Number(Number($('.laytable-cell-2-0-'+v).last().text())-Number(oldtext)+Number(editValue)).toFixed(decimalObj[i]));
					}else{
						var totalSum=0;
						$.each($('.laytable-cell-2-0-'+v),function(j,k){
							if(j>0 && j<$('.laytable-cell-2-0-'+v).length-1)totalSum+=Number($(k).text());//第一个是标题，最后一个是统计行
							if(j==$('.laytable-cell-2-0-'+v).length-1)$(k).text(totalSum.toFixed(decimalObj[i]));
						})
					}
				})
			}
			setTableValue('dhtable1', dataindex, editField, editValue);//通过dom给表格内控件渲染值
			listData1[dataindex][editField] = editValue;
		}
	});
})
function beforeSave(tableData){//单据保存提交前的操作
	tableData={};
	tableData['takeDownItems']=listData;
	tableData['takeOnItems']=listData1;
	return tableData;
}
function beforeDelete(pd){//单据删除提交前的操作
	var iitems={};
	iitems['takeDownItems']=[];
	iitems['takeOnItems']=[];
	return {'infoMap':JSON.stringify($(".head-form").serializeFormToJson()),'infoItems':JSON.stringify(iitems)};
}
</script>
</body>
</html>